const app = getApp();
Component({
	properties: {
		tags: {
			type: Array,
			default: () => []
		},
		showMore: {
			type: Boolean,
			default: false
		}
	},
	data: {
		safeArea: app.globalData.safeArea,
		scrollLeft: 0,
		barIndex: -1,
		barOffset: 0,
		barWidth: 0,
		tagsBoundingClientRect: []
	},
	pageLifetimes: {
		show() {
			wx.nextTick(async () => {
				if (this.data.barIndex > -1) {
					return;
				}
				await this.onInitBoundingClientRect()
				this.onTagCheck(0)
			})
		}
	},
	methods: {
		// 分类项目点击
		async onTap(e) {
			if (this.data.tagsBoundingClientRect.length === 0) {
				await this.onInitBoundingClientRect()
			}
			const index = e.currentTarget.dataset.index || 0;
			this.onTagCheck(index);
			this.triggerEvent("onTap", {index, item: this.data.tags[index]})
		},
		// 更多按钮点击
		onMore() {
			this.triggerEvent("onMore")
		},
		// 指定选中项目（提供该方法是为了方便使用）
		onTagCheck(index) {
			const item = this.data.tagsBoundingClientRect[index];
			if (!item) {
				return;
			}
			const width = this.data.safeArea.width || 0;
			const halfItemWidth = item.width / 2
			this.setData({
				scrollLeft: item.left - (width / 2) + halfItemWidth,
				barIndex: index,
				barOffset: item.left + halfItemWidth / 3,
				barWidth: halfItemWidth,
			})
		},
		// 计算每一项的位置区域信息
		onInitBoundingClientRect() {
			return new Promise((resolve => {
				const query = wx.createSelectorQuery().in(this)
				query.selectAll('.container .item').boundingClientRect((res) => {
					this.data.tagsBoundingClientRect = res;
					resolve(res)
				}).exec()
			}))

		}
	}
});
